package es.mllacer.qqsm.runnables;

import android.content.Context;
import android.content.SharedPreferences;
import es.mllacer.qqsm.Play;
import es.mllacer.qqsm.util.HighScore;
import es.mllacer.qqsm.util.HighScoreList;
import es.mllacer.qqsm.util.LocalScoresDBHelper;
import es.mllacer.qqsm.util.Utils;

public class LocalScoreRunnable implements Runnable {

	private Play activity = null;
	private int score = 0;

	public LocalScoreRunnable(Play activity) {
		this.activity = activity;
	}

	public void sendScore(int score) {
		this.score = score;
		Thread thread = new Thread(this);
		thread.start();
	}

	@Override
	public void run() {
		SharedPreferences settingsPrefs = activity.getSharedPreferences(
				Utils.SETTINGS_PREFERENCES, Context.MODE_PRIVATE);

		String name = settingsPrefs.getString(Utils.USER_PREFERENCE, "");
		float longitude = settingsPrefs.getFloat(Utils.LONGITUDE_PREFERENCE, 0);
		float latitude = settingsPrefs.getFloat(Utils.LATITUDE_PREFERENCE, 0);
		String address = Utils.getAddress(activity, latitude, longitude);

		HighScoreList list = LocalScoresDBHelper.getInstance(activity)
				.getLocalScores();
		for (HighScore hs : list.getScores()) {
			if (name.equals(hs.getName()) && score == hs.getScoring()) {
				// this score has already been stored before
				return;
			}
		}

		LocalScoresDBHelper.getInstance(activity).insertLocalScore(name,
				longitude, latitude, address, score);
	}

}
